import { Auths, Role } from '@/utils/types.d';
import {
  ProCard,
  ProForm,
  ProFormDigit,
  ProFormGroup,
  ProFormList,
  ProFormSelect,
  FooterToolbar,
} from '@ant-design/pro-components';
import { Button, message } from 'antd';
import { useEffect, useState } from 'react';
import { useModel } from 'umi';
import { queryCompanies } from '../SystemUser/service';
import { checkAndTransferConfig } from './utils';
import { getStatsConfig, editStatsConfig } from './service';
import { StatsConfig } from './types.d';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
const DEFAULT = {
  times: [],
  amounts: [],
};
const validator = (_: any, value: any[]) => {
  try {
    if (!value || value.length == 0 || value.length > 8) {
      return Promise.reject(new Error('统计区间配置数量不正确'));
    }
    for (let i = 0; i < value.length; i++) {
      const item = value[i];
      if (item.start === undefined || item.end === undefined) {
        return Promise.reject(new Error('区间起始、结束值不可为空'));
      }
      if (item.start >= item.end) {
        return Promise.reject(new Error('区间起始值必须小于区间结束值'));
      }
      if (i > 0 && value[i - 1].end != item.start) {
        return Promise.reject(new Error('区间起始值必须等于上一区间结束值'));
      }
    }
    return Promise.resolve();
  } catch (err) {
    return Promise.reject(new Error(String(err)));
  }
};
const StatsConfigPage = () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const isAdmin = currUser?.role === Role.ADMIN;
  const [ownerId, setOwnerId] = useState<string>(isAdmin ? '' : currUser?.ownerId || '');
  const [form] = ProForm.useForm();
  const [chillDowning, setChillDowning] = useState<number>(0);
  const auths = currUser?.auth ? new Set(currUser.auth.systemConfig || []) : new Set();
  const ifConfig = auths.has(Auths.STATS_CONFIG);
  const [currConfig, setCurrConfig] = useState<StatsConfig>(DEFAULT);
  if (chillDowning > -1) {
    setTimeout(() => {
      setChillDowning(chillDowning - 1);
    }, 1000);
  }
  useEffect(() => {
    if (!ownerId) return;
    getStatsConfig(ownerId).then((res) => {
      if (!res || !res.data) return;
      const temp = {
        times: res?.data?.times || currConfig.times,
        amounts: res?.data?.amounts || currConfig.amounts,
      };
      form?.setFieldsValue({
        times: temp.times.filter((it) => it.end != undefined),
        amounts: temp.amounts
          ?.filter((it) => it.end != undefined)
          ?.map((it) => {
            return {
              start: (it.start || 0) / 100,
              end: (it.end || 0) / 100,
            };
          }),
      });
    });
  }, [ownerId]);

  return (
    <PageHeaderWrapper
      header={{
        breadcrumb: {
          routes: [
            {
              path: '/',
              breadcrumbName: '首页',
            },
            {
              path: '/setting-config',
              breadcrumbName: '系统配置',
            },
            {
              path: '/stats',
              breadcrumbName: '统计区间配置',
            },
          ],
        },
        subTitle: '统计区间配置',
      }}
      extra={
        isAdmin && (
          <ProFormSelect
            name="ownerId"
            label="配置公司"
            debounceTime={300}
            showSearch
            fieldProps={{
              value: ownerId,
              onChange: (val) => {
                if (ownerId != '') {
                  form?.setFieldsValue(DEFAULT);
                }
                setOwnerId(val);
              },
              style: {
                width: 280,
                margin: 0,
              },
            }}
            placeholder="请选择要进行配置公司"
            request={(val) => queryCompanies(val.keyWords, false)}
          />
        )
      }
    >
      <ProCard direction="column">
        <ProCard ghost title="配置说明">
          <p>
            1. 最多配置8个区间（自动追加区间不计入限制数），区间的开始值必须小于结束值，且不能重叠
          </p>
          <p>2. 当首个区间数组不以0为起始值时，将自动添加 [0, 首个区间起始值] 作为首段区间</p>
          <p>3. 保存时将自动追加 [末尾区间结束值，∞] 作为终段区间 </p>
          <p>注意：更改配置后次日开始生效</p>
        </ProCard>
        <ProForm<{
          times: { start: number; end: number }[];
          amounts: { start: number; end: number }[];
        }>
          form={form}
          submitter={{
            searchConfig: {
              submitText: ifConfig ? '保存配置' : '无权限操作',
            },
            submitButtonProps: {
              disabled: !ifConfig || chillDowning > 0,
            },
            render: (_, dom) => (
              <FooterToolbar>
                <Button
                  onClick={() => {
                    form.validateFields(['times', 'amounts']);
                  }}
                >
                  验证
                </Button>
                {dom}
              </FooterToolbar>
            ),
          }}
          initialValues={{
            times: currConfig?.times?.filter((it) => it.end != undefined),
            amounts: currConfig?.amounts
              ?.filter((it) => it.end != undefined)
              ?.map((it) => {
                return {
                  start: (it.start || 0) / 100,
                  end: (it.end || 0) / 100,
                };
              }),
          }}
          onFinish={async (values) => {
            if (!ownerId) {
              message.warn({ content: '请选择配置公司', key: 'checkOwnerRes' });
              return;
            }
            const checkTimeRes = checkAndTransferConfig(values.times);
            if (!checkTimeRes.valid) {
              message.warn({ content: checkTimeRes.message, key: 'checkTimeRes' });
              return;
            }
            const checkAmountRes = checkAndTransferConfig(values.amounts, 100);
            if (!checkAmountRes.valid) {
              message.warn({ content: checkAmountRes.message, key: 'checkAmountRes' });
              return;
            }
            setCurrConfig({
              times: checkTimeRes.data,
              amounts: checkAmountRes.data,
            });
            setChillDowning(10);
            const res = await editStatsConfig({
              ownerId,
              times: checkTimeRes.data,
              amounts: checkAmountRes.data,
            });
            if (!res.success) {
              message.error({ content: res.message, key: 'editStatsConfig' });
              return false;
            }
            message.success({ content: '保存成功', key: 'editStatsConfig' });
            return true;
          }}
        >
          <ProFormList
            label={<h3>订单时长统计区间配置</h3>}
            name="times"
            min={0}
            max={8}
            creatorButtonProps={{
              creatorButtonText: '添加订单时长统计区间',
              style: {
                marginBottom: 5,
              },
            }}
            rules={[
              {
                validator,
              },
            ]}
          >
            <ProFormGroup labelLayout="inline">
              <ProFormDigit
                min={0}
                fieldProps={{ precision: 0 }}
                name="start"
                addonAfter="分钟(不包含) "
              />
              <span>-</span>
              <ProFormDigit min={0} fieldProps={{ precision: 0 }} addonAfter="分钟" name="end" />
            </ProFormGroup>
          </ProFormList>

          <ProFormList
            label={<h3>订单金额统计区间配置</h3>}
            name="amounts"
            tooltip="金额为0的订单计入免费订单统计，不包含在该项统计内"
            creatorButtonProps={{
              creatorButtonText: '添加订单金额统计区间',
              style: {
                marginBottom: 5,
              },
            }}
            min={0}
            max={8}
            rules={[{ validator }]}
          >
            <ProFormGroup labelLayout="inline">
              <ProFormDigit
                min={0}
                fieldProps={{ precision: 0 }}
                name="start"
                addonAfter="元(不包含) "
              />
              <span>-</span>
              <ProFormDigit min={0} fieldProps={{ precision: 0 }} addonAfter="元" name="end" />
            </ProFormGroup>
          </ProFormList>
        </ProForm>
      </ProCard>
    </PageHeaderWrapper>
  );
};

export default StatsConfigPage;
